package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author : jam.chen
 * @Project : changgou_parent
 * @ClassName : AuthorizeFilter
 * @PackageName : com.changgou.system.filter
 * @date : 2020/7/20  23:44
 * @Version : 1.0
 */

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2、获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //3、判断当前的请求是否为登录请求，如果是则直接放行
        if (request.getURI().getPath().contains("/admin/login")){
            return chain.filter(exchange);
        }
        //4、获取当前的所有请求头信息
        HttpHeaders headers = request.getHeaders();
        //5、获取jwt令牌
        String token = headers.getFirst("token");
        //6、判断当前令牌是否存在，如果不存在则向客户端发送错误提示信息。
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //7、如果令牌存在解析令牌，判断是否合法，如果不合法则向客户端返回错误提示信息。
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //8、如果令牌合法则放行


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
